<?php
/**
 * 考勤系统App用户
 */
namespace app\attendance\controller;

use app\attendance\Base;
use think\Config;
use think\Db;
use think\Loader;
use think\exception\HttpException;
use baseutils\BaseUtil; # 验证类

use com\gdl\kq\interfaces\AttAppUserServiceClient;
use com\gdl\kq\dataobject\user\UserDTO; 
use com\gdl\kq\dataobject\user\UserLoginDTO; 
use com\gdl\kq\dataobject\user\UserSendSmsDTO; 
use com\gdl\kq\dataobject\user\UserPhoneLogin;  


class AttAppUser extends Base
{
	
	/**
	 * 用户身份证 手机号登录
	 * @return [type] [description]
	 */
	public function userLogin()
    {
    	$msg =  ['msg'=>'登录异常','code'=>'400','data'=>[]];

		#其他参数
		$username = $this->request->param('username') ? getStr($this->request->param('username')) : ''; 
		$password = $this->request->param('password') ? getStr($this->request->param('password')) : '';

		if(empty($username)){$msg['msg']= "请输入身份证或绑定的手机号"; json_encode($msg);}
		if(empty($password) || strlen($password)<6){ $msg['msg'] = "请输入大于六位数的密码"; return json_encode($msg);}

		#其他参数
		try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserLoginDTO();
			$userDO->username = $username; 
			$userDO->password = $password;
			$util = new BaseUtil(); 
            if ($util->IsMobile($username)) {
                $userDO->type = 'phone';
            } elseif ($util->isIdCard($username)) {
                $userDO->type = 'idcard';
            } else {
                $userDO->type = 'jobnumber';
            } 

            #调用接口
			$result = $api->userLogin($userDO);
			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data;
				if($result->code==200){
					$msg['data'] = json_decode($result->data[0]['userInfo']);
				}
			}
		} catch (Exception $ex) {
			 $msg['msg'] = $ex->getMessage();
		}

		return json_encode($msg);
	}
	/**
	 * 手机验证码登录 第一步：调用sendSmd发送短信 第二步：调用此接口登录
	 * @return [type] [description]
	 */
	public function userPhoneLogin(){
		$msg =  ['msg'=>'登录异常','code'=>'400','data'=>[]];

		#其他参数
		$phone = $this->request->param('phone') ? getStr($this->request->param('phone')) : ''; 
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : '';
		$code = $this->request->param('code') ? getStr($this->request->param('code')) : '';

		#验证
		$util = new BaseUtil(); 
        if (!$util->IsMobile($phone)) {$msg['msg'] = "请输入正确的手机号"; return json_encode($msg);}
        if(empty($userId)){$msg['msg'] = "手机号未绑定"; return json_encode($msg);}
        if(empty($code) || strlen($code)!=6){$msg['msg'] = "请输入六位数字验证码"; return json_encode($msg);}

        try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserPhoneLogin();
			$userDO->phone = $phone; 
			$userDO->userid = $userId;
			$userDO->code = $code;

            #调用接口
			$result = $api->userPhoneLogin($userDO);
			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data;
				if($result->code==200){
					$msg['data'] = json_decode($result->data[0]['userInfo']);
				}
			}
		} catch (Exception $ex) {
			 $msg['msg'] = $ex->getMessage();
		}

		return json_encode($msg);

	}

	/**
	 * App发送短信接口 短信前缀还是【安管控】开头，需要更改
	 * [type:login]登录短信 [type:bing]绑定短信 [type:reg]注册短信  [type:repassword]修改密码 [type:isBing]验证绑定手机  暂时废弃[type:retrieve]忘记密码or找回密码
	 */
	public function sendSms(){
		$msg =  ['msg'=>'发送失败','code'=>'400','data'=>[]];
		# 公共参数
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

		#其他参数
		$phone = $this->request->param('phone') ? getStr($this->request->param('phone')) : ''; 
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : ''; 
		$type = $this->request->param('type') ? getStr($this->request->param('type')) : ''; 
		//$token = md5('3'."yucdxznijkow15f6izjnlx40misyryds");
		#验证
		if($type=="bing" || $type=="isBing"){
			if(!checkToken($token,$userId)){$msg['msg'] ='用户登录失效，请重新登录'; $msg['code']=501; return json_encode($msg);}	
		}

		$util = new BaseUtil(); 
        if (!$util->IsMobile($phone)) {
            $msg['msg'] = "请输入正确的手机号";
            return json_encode($msg);
        }
        if(!empty($type)){
        	if($type=="bing" || $type=="retrieve"){
        		if(empty($userId)){$msg['msg'] = "请选择用户"; return json_encode($msg);}
        	}
        }else{
        	$msg['msg'] = "请选择正确的发送方式";
            return json_encode($msg);	
        }

		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserSendSmsDTO();
			$userDO->phone = $phone;
			$userDO->userid = $userId;
			$userDO->type = $type;

			 #调用接口
			$result = $api->sendSms($userDO);
			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data;
				if(!empty($result->data)){
					$msg['data'] = $result->data[0];
				}
			}

		} catch (Exception $ex) {
			 $msg['msg'] = $ex->getMessage();
		}

		return json_encode($msg);
	}
	//绑定手机号 第一步：绑定手机
	public function isBingPhone(){
		$msg =  ['msg'=>'验证失败，请确认是本人操作','code'=>'400','data'=>[]];
		# 公共参数
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

		#其他参数
		$phone = $this->request->param('phone') ? getStr($this->request->param('phone')) : ''; 
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : ''; 
		$code = $this->request->param('code') ? getStr($this->request->param('code')) : ''; 
			
		$util = new BaseUtil(); 
        if (!$util->IsMobile($phone)) {
            $msg['msg'] = "请输入正确的手机号";
            return json_encode($msg);
        }
        if(empty($userId)){$msg['msg'] = "手机号未绑定"; return json_encode($msg);}
        if(empty($code) || strlen($code)!=6){$msg['msg'] = "请输入六位数字验证码"; return json_encode($msg);}
        #验证
		if(!checkToken($token,$userId)){$msg['msg'] ='用户登录失效，请重新登录'; $msg['code']=501; return json_encode($msg);}
         

		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserPhoneLogin();
			$userDO->phone = $phone;
			$userDO->userid = $userId;
			$userDO->code = $code;

			 #调用接口
			$result = $api->isBingPhone($userDO);
			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data; 
			}

		} catch (Exception $ex) {
			 $msg['msg'] = $ex->getMessage();
		}

		return json_encode($msg);
	}
	// 绑定手机号 第二步：开始绑定手机
	public function bingPhone(){
		$msg =  ['msg'=>'绑定失败','code'=>'400','data'=>[]];
		# 公共参数
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

		#其他参数
		$phone = $this->request->param('phone') ? getStr($this->request->param('phone')) : ''; 
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : ''; 
		$code = $this->request->param('code') ? getStr($this->request->param('code')) : ''; 
		
		#验证
		if(!checkToken($token,$userId)){$msg['msg'] ='用户登录失效，请重新登录'; $msg['code']=501; return json_encode($msg);}	
		$util = new BaseUtil(); 
        if (!$util->IsMobile($phone)) {
            $msg['msg'] = "请输入正确的手机号";
            return json_encode($msg);
        }
        if(empty($userId)){$msg['msg'] = "手机号未绑定"; return json_encode($msg);}
        if(empty($code) || strlen($code)!=6){$msg['msg'] = "请输入六位数字验证码"; return json_encode($msg);}
         

		try{
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserPhoneLogin();
			$userDO->phone = $phone;
			$userDO->userid = $userId;
			$userDO->code = $code;

			 #调用接口
			$result = $api->bingPhone($userDO);
			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data;
				if(!empty($result->data)){
					$msg['data'] = $result->data[0];
				}
			}

		} catch (Exception $ex) {
			 $msg['msg'] = $ex->getMessage();
		}

		return json_encode($msg);
	}

	//短信找回密码
	public function userForgetPassword(){
		$msg =  ['msg'=>'修改失败','code'=>'400','data'=>[]];

		#其他参数
		$phone = $this->request->param('phone') ? getStr($this->request->param('phone')) : ''; 
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : ''; 
		$code = $this->request->param('code') ? getStr($this->request->param('code')) : '';
		$password =  $this->request->param('password') ? getStr($this->request->param('password')) : '';
		$rePassword =  $this->request->param('rePassword') ? getStr($this->request->param('rePassword')) : '';
		
		#验证
		$util = new BaseUtil(); 
        if (!$util->IsMobile($phone)) {
            $msg['msg'] = "请输入正确的手机号";
            return json_encode($msg);
        }
        if(empty($userId)){$msg['msg'] = "验证码错误"; return json_encode($msg);}
        if(empty($code) || strlen($code)!=6){$msg['msg'] = "请输入六位数字验证码"; return json_encode($msg);}
        if(empty($password) || strlen($password)<6){$msg['msg'] = "请输入6位新密码"; return json_encode($msg);}
        if(empty($rePassword) || strlen($rePassword)<6){$msg['msg'] = "请重复6新密码"; return json_encode($msg);}
        if($password != $rePassword){$msg['msg'] = "两次密码不一致"; return json_encode($msg);}

        $sdkData = [
        	'phone'=>$phone,
        	'userId'=>$userId,
        	'code'=>$code,
        	'password'=>$password,
        	'rePassword'=>$rePassword,
        ];
        try{

        	\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserDTO();
			$userDO->data = $sdkData; 
			 #调用接口
			$result = $api->userForgetPassword($userDO);

			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data;
			}

        }catch(Exception $e){
        	$msg['msg'] = $e->getMessage();
        }

        return json_encode($msg);
	}
	
	//照片采集
	public function userUploadPhoto(){
		# 公共参数
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : ''; 
        $msg = ['code'=>400,'msg' => '上传失败图片格式不正确', 'data' => []];

        #验证
        if(!checkToken($token,$userId)){$msg['msg'] ='用户登录失效，请重新登录'; $msg['code']=501; return json_encode($msg);}
        if(empty($userId)){$msg['msg']="缺少userId"; return json_encode($msg);} 

		try{
			$upload = new Upload();
        	$uploadFile = $upload->qiniuUploadfile();
        	$uploadFile = json_decode($uploadFile,true);

        	if($uploadFile['code']!=200){$msg['msg'] = "图片上传失败"; return json_encode($msg);}

	        	if(!empty($uploadFile['data']['url'])){
        			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
					$api = new AttAppUserServiceClient(NULL);
					\ApiClient::build($api);
					$sdkData = ['url'=>$uploadFile['data']['url'], 'userId'=>$userId];
					$userDO = new UserDTO();
					$userDO->data = $sdkData;

					$result = $api->userUploadPhoto($userDO); 
					if($result->success ==true){	
						$msg['code'] = $result->code;
						$msg['msg'] = $result->message;
						$msg['data'] = $result->data;
						if(!empty($result->data)){
							$msg['data'] = $result->data[0];
						}
					}else{
						$msg['msg'] = "上传图片失败";
					}
	        	}else{
	        		$msg['msg'] ="图片上传失败";
	        	}
        	}catch(Exception $e){
        			$msg['msg'] = $e->getMessage();
        	}

        return json_encode($msg);
	}

	//根据旧密码修改新密码
	public function userRePassword(){
		$msg =  ['msg'=>'修改失败','code'=>'400','data'=>[]];
		# 公共参数
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

		#其他参数
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : '';  #用户id
		$oldPassword = $this->request->param('oldPassword') ? getStr($this->request->param('oldPassword')) : '';  #旧密码
		$newPassword = $this->request->param('newPassword') ? getStr($this->request->param('newPassword')) : ''; #新密码
		$rePassword = $this->request->param('rePassword') ? getStr($this->request->param('rePassword')) : ''; #重复新棉

		#验证
		if(!checkToken($token,$userId)){$msg['msg'] ='用户登录失效，请重新登录'; $msg['code']=501; return json_encode($msg);}
		if(empty($userId)){$msg['msg'] = "请选择需要修改密码的用户"; return json_encode($msg);}
		if(empty($oldPassword)){$msg['msg'] = "请输入旧密码"; return json_encode($msg);}
		if(empty($newPassword) || strlen($newPassword)<6){$msg['msg'] = "请输入6位以上的新密码"; return json_encode($msg);}
		if(empty($rePassword) || strlen($rePassword)<6){$msg['msg'] = "请重复6位以上的新密"; return json_encode($msg);}
		if($newPassword !=$rePassword){$msg['msg'] = "两次密码不一致"; return json_encode($msg);}

		try{
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
				$api = new AttAppUserServiceClient(NULL);
				\ApiClient::build($api);
				$sdkData = ['userId'=>$userId, 'oldPassword'=>$oldPassword, 'newPassword'=>$newPassword, 'rePassword'=>$rePassword];
				$userDO = new UserDTO();
				$userDO->data = $sdkData;

				$result = $api->userRePassword($userDO); 
				if($result->success ==true){	
					$msg['code'] = $result->code;
					$msg['msg'] = $result->message;
					$msg['data'] = $result->data; 
				} 
		}catch(Exception $e){
			$msg['msg'] = $e->getMessage();
		}
		return json_encode($msg);
	}
	//app用户中心用户详情
	public function userInfo(){
		$msg =  ['msg'=>'用户不存在','code'=>'400','data'=>[]];

		#公共
		$token = $this->request->param('token') ? getStr($this->request->param('token')) : '';

		#其他参数
		$userId = $this->request->param('userId') ? getStr($this->request->param('userId')) : ''; 

		if(empty($userId)){$msg['msg']= "用户未登录"; json_encode($msg);}
		if(!checkToken($token,$userId)){$msg['msg'] ='用户登录失效，请重新登录'; $msg['code']=501; return json_encode($msg);}

		#其他参数
		try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlCloudSdk'));
			$api = new AttAppUserServiceClient(NULL);
			\ApiClient::build($api); 
			$userDO = new UserDTO();
			$sdkData = ['userId'=>$userId]; 
			$userDO->data = $sdkData;
            #调用接口
			$result = $api->userInfo($userDO);
			if($result->success==true){
				$msg['code'] = $result->code;
				$msg['msg'] = $result->message;
				$msg['data'] = $result->data;
				if($result->code==200){
					$msg['data'] = json_decode($result->data[0]['userInfo']);
				}
			}
		} catch (Exception $ex) {
			 $msg['msg'] = $ex->getMessage();
		}

		return json_encode($msg);
	}
}
